/**
 * Copyright (C) 2017 - 2020 https://github.com/joewee
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.service.impl;

import com.bifrost.common.util.HttpRequestUtils;
import com.bifrost.entity.IndexSetting;
import com.bifrost.entity.IndexSettingRegion;
import com.bifrost.entity.MerchantStore;
import com.bifrost.repository.IndexSettingRegionRepository;
import com.bifrost.repository.IndexSettingRepository;
import com.bifrost.repository.MerchantStoreRepository;
import com.bifrost.service.IndexSettingRegionService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author joewee
 * @version 1.0.0
 * @Date 2017/10/20 10:56
 */
@Service
public class IndexSettingRegionServiceImpl implements IndexSettingRegionService {

    private static final Logger LOGGER= LoggerFactory.getLogger(IndexSettingRegionServiceImpl.class);

    @Autowired
    IndexSettingRegionRepository indexSettingRegionRepository;
    @Autowired
    MerchantStoreRepository merchantStoreRepository;
    @Autowired
    IndexSettingRepository indexSettingRepository;

    @Override
    public List<IndexSettingRegion> findAllVisible() {
        return indexSettingRegionRepository.findByIsVisibleOrderBySortOrderAsc(Boolean.TRUE);
    }
    @Override
    public List<IndexSettingRegion> findAllVisibleByStore(MerchantStore store) {
        return indexSettingRegionRepository.findByIsVisibleAndMerchantStoreOrderBySortOrderAsc(Boolean.TRUE,store);
    }

    /**
     * 获取首页所有配置
     *
     * @param merchantId
     * @param storeName
     * @param page
     * @param pageSize
     * @param visible
     * @return
     */
    @Override
    public Page<IndexSettingRegion> findAll(Long merchantId, String storeName, Integer page, Integer pageSize, Boolean visible) {
        Pageable pageable=new PageRequest(page - 1,pageSize,new Sort(Sort.Direction.ASC,"sortOrder"));
        Specification<IndexSettingRegion> query=new Specification<IndexSettingRegion>() {
            @Override
            public Predicate toPredicate(Root<IndexSettingRegion> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                List<Predicate> predicates=new ArrayList<>();
                if (merchantId!=null){
                    MerchantStore store=merchantStoreRepository.findOne(merchantId);
                    predicates.add(cb.equal(root.get("merchantStore"),store));
                }
                if (StringUtils.isNotBlank(storeName)){
                    List<MerchantStore> stores=merchantStoreRepository.findByStoreName("%"+storeName+"%");
                    if(CollectionUtils.isEmpty(stores)){
                        return null;
                    }
                    List<IndexSettingRegion> list=indexSettingRegionRepository.findAll();
                    stores.forEach(s->{
                        list.forEach(i->{
                            if (s.getMerchantId().equals(i.getMerchantStore().getMerchantId())){
                                predicates.add(cb.equal(root.get("merchantStore"),s));
                            }
                        });
                    });
                }

                if(visible!=null){
                    predicates.add(cb.equal(root.get("isVisible"),visible));
                    /*if(Boolean.TRUE.equals(visible)){
                        predicates.add(cb.isTrue());
                    }else {
                        predicates.add(cb.isFalse(root.get("isVisible")));
                    }*/
                }

                Predicate[] p=new Predicate[predicates.size()];
                return cb.and(predicates.toArray(p));
            }
        };
        return indexSettingRegionRepository.findAll(query,pageable);
    }

    /**
     * 新增/更新首页
     *
     * @param region
     * @return
     */
    @Override
    public IndexSettingRegion save(IndexSettingRegion region) {
        return indexSettingRegionRepository.save(region);
    }

    /**
     * 根据ID查找配置
     *
     * @param id
     * @return
     */
    @Override
    public IndexSettingRegion findById(Long id) {
        return indexSettingRegionRepository.findOne(id);

    }

    /**
     * 检查门店配置信息是否存在
     *
     * @param store param ids
     * @param ids
     * @return
     */
    @Override
    public List<IndexSettingRegion> findAllByStoreAndIndexRegionId(MerchantStore store, Collection ids) {
        return indexSettingRegionRepository.findAllByMerchantStoreAndIndexRegionId(store,ids);

    }

    /**
     * 删除配置信息
     *
     * @param ids
     * @param store
     */
    @Override
    public void deleteByIdAndStore(Collection ids, MerchantStore store) {
        indexSettingRegionRepository.deleteByIndexRegionIdAAndMerchantStore(ids,store);

    }

    /**
     * 获取指定门店配置
     *
     *
     * @param visible
     * @param indexRegionId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page<IndexSetting> findByIndexRegionId(String visible, Long indexRegionId, Integer page, Integer pageSize) {
        Pageable pageable=new PageRequest(page - 1,pageSize,new Sort(Sort.Direction.ASC,"sortOrder"));
        Specification<IndexSetting> query=new Specification<IndexSetting>() {
            @Override
            public Predicate toPredicate(Root<IndexSetting> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (indexRegionId != null) {
                    IndexSettingRegion region=indexSettingRegionRepository.findOne(indexRegionId);
                    predicates.add(cb.equal(root.get("indexSettingRegion"), region));
                }
                if(StringUtils.isNotBlank(visible)){
                    if(Boolean.TRUE.equals(visible)){
                        predicates.add(cb.isTrue(root.get("isVisible")));
                    }else {
                        predicates.add(cb.isFalse(root.get("isVisible")));
                    }
                }
                Predicate[] p = new Predicate[predicates.size()];
                return cb.and(predicates.toArray(p));
            }
        };
        return indexSettingRepository.findAll(query,pageable);
    }

    /**
     * 根据指定门店增加/修改详细配置
     *
     * @param setting
     * @return
     */
    @Override
    public IndexSetting save(IndexSetting setting) throws IOException {
        if (setting.getIndexSettingId()!=null){
            IndexSetting check=indexSettingRepository.findOne(setting.getIndexSettingId());
        }
        setting.setImg(setting.getImg().replace(HttpRequestUtils.getUrlAccessPath(),""));
        return indexSettingRepository.save(setting);
    }

    /**
     * 检查指定门店配置信息是否存在
     *
     * @param region
     * @return
     */
    @Override
    public List<IndexSetting> finfByIndexRegionId(IndexSettingRegion region) {
        return indexSettingRepository.findAllByIndexSettingRegion(region);

    }

    /**
     * 检查指定门店配置信息是否存在
     *
     * @param indexSettingId
     * @return
     */
    @Override
    public IndexSetting findByIndexSettingId(Long indexSettingId) {
        return indexSettingRepository.findOne(indexSettingId);

    }

    /**
     * 检查指定门店详细配置
     *
     * @param indexSettingId
     * @param region
     * @return
     */
    @Override
    public IndexSetting findByIndexSettingIdAndIndexSettingRegion(Long indexSettingId, IndexSettingRegion region) {
        return indexSettingRepository.findByIndexSettingIdAndIndexSettingRegion(indexSettingId,region);

    }

    /**
     * 删除指定门店配置信息
     *
     * @param indexSettingIds
     * @return
     */
    @Override
    public void deleteByIndexSettingId(Collection indexSettingIds) {
        if (CollectionUtils.isNotEmpty(indexSettingIds)){
            indexSettingRepository.deleteByIndexSettingId(indexSettingIds);
        }
        LOGGER.info("门店详细配置不能为空");
    }
}
